package controller;
import pojo.GoodsSingle;
import save.MyTools;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.ArrayList;

@WebServlet("/AddGoodsServlet")
@MultipartConfig
public class AddGoodsServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");  // 防止乱码
        String name = request.getParameter("name");
        float price = Float.parseFloat(request.getParameter("price"));
        int quantity = Integer.parseInt(request.getParameter("quantity"));

        Part filePart = request.getPart("image");
        String fileName = extractFileName(filePart);

        // 保存图片文件到应用的动态img目录
        String appPath = request.getServletContext().getRealPath("");
        String savePath = appPath + "img" + File.separator + fileName;
        saveFile(filePart, savePath);

        GoodsSingle newGoods = new GoodsSingle();
        newGoods.setName(name);
        newGoods.setPrice(price);
        newGoods.setNum(quantity);
        newGoods.setImgename("img/" + fileName);

        ArrayList<GoodsSingle> goodslist = null;
        ServletContext contex = this.getServletContext();
        if(null==contex.getAttribute("goodslist")){
            try {
                goodslist = MyTools.getGoods(); // 初始化原来的商品列表

                newGoods.setNum(1);  // 购买数量信息初始化为1
                goodslist.add(newGoods);  // 将新添加的商品也放进去
            } catch (Exception e) {
                e.printStackTrace();
            }
            contex.setAttribute("goodslist",goodslist);
        }
        // 请求转发到show.jsp页面
        request.getRequestDispatcher("show.jsp").forward(request, response);
    }

    private String extractFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String s : items) {
            if (s.trim().startsWith("filename")) {
                return s.substring(s.indexOf("=") + 2, s.length() - 1);
            }
        }
        return "";
    }
    private void saveFile(Part filePart, String filePath) throws IOException {
        InputStream input = filePart.getInputStream();
        File file = new File(filePath);

        try (OutputStream output = new FileOutputStream(file)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        }
    }
}
